package com.example.userdepartment.controller;

import com.example.userdepartment.entity.User;
import com.example.userdepartment.service.UserService;
import com.example.userdepartment.util.ExcelUtil;
import com.example.userdepartment.util.Result;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * 用户管理控制器
 */
@RestController
@RequestMapping("/api/users")
public class UserController {

    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private UserService userService;

    /**
     * 获取所有用户
     */
    @GetMapping
    public Result<List<User>> getAllUsers() {
        return Result.success(userService.findAll());
    }

    /**
     * 搜索用户
     */
    @GetMapping("/search")
    public Result<List<User>> searchUsers(
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) Integer departmentId) {
        logger.info("搜索用户 - 关键字: {}, 部门ID: {}", keyword, departmentId);
        List<User> users = userService.searchUsers(keyword, departmentId);
        return Result.success(users);
    }

    /**
     * 根据ID获取用户
     */
    @GetMapping("/{id}")
    public Result<User> getUserById(@PathVariable Integer id) {
        User user = userService.findById(id);
        if (user != null) {
            return Result.success(user);
        }
        return Result.error("用户不存在");
    }

    /**
     * 根据ID获取用户及部门信息
     */
    @GetMapping("/{id}/with-dept")
    public Result<User> getUserWithDeptById(@PathVariable Integer id) {
        User user = userService.findWithDeptById(id);
        if (user != null) {
            return Result.success(user);
        }
        return Result.error("用户不存在");
    }

    /**
     * 添加用户
     */
    @PostMapping
    public Result<User> addUser(@RequestBody User user) {
        return Result.success("添加成功", userService.add(user));
    }

    /**
     * 更新用户
     */
    @PutMapping("/{id}")
    public Result<User> updateUser(@PathVariable Integer id, @RequestBody User user) {
        user.setId(id);
        return Result.success("更新成功", userService.update(user));
    }

    /**
     * 删除用户
     */
    @DeleteMapping("/{id}")
    public Result<Void> deleteUser(@PathVariable Integer id) {
        boolean success = userService.delete(id);
        if (success) {
            return Result.success("删除成功", null);
        }
        return Result.error("删除失败");
    }

    /**
     * 批量删除用户
     */
    @DeleteMapping("/batch")
    public Result<Void> batchDeleteUsers(@RequestBody List<Integer> ids) {
        boolean success = userService.batchDelete(ids);
        if (success) {
            return Result.success("批量删除成功", null);
        }
        return Result.error("批量删除失败");
    }

    /**
     * 根据部门ID获取用户列表
     */
    @GetMapping("/by-department/{departmentId}")
    public Result<List<User>> getUsersByDepartmentId(@PathVariable Integer departmentId) {
        return Result.success(userService.findByDepartmentId(departmentId));
    }

    /**
     * 导入用户
     */
    @PostMapping("/import")
    public Result importUsers(@RequestParam("file") MultipartFile file) {
        return userService.importUsers(file);
    }

    /**
     * 获取用户导入模板
     */
    @GetMapping("/import/template")
    public void getUserImportTemplate(HttpServletResponse response) {
        try {
            logger.info("开始生成用户导入模板");
            Workbook workbook = ExcelUtil.generateUserImportTemplate();
            
            // 设置响应头
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setHeader("Content-Disposition", "attachment; filename=user_import_template.xlsx");
            response.setHeader("Pragma", "no-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0);
            
            // 写入响应流
            workbook.write(response.getOutputStream());
            workbook.close();
            response.getOutputStream().flush();
            logger.info("用户导入模板生成成功");
        } catch (IOException e) {
            logger.error("生成用户导入模板失败", e);
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }

    /**
     * 导出用户Excel
     */
    @GetMapping("/export")
    public ResponseEntity<byte[]> exportUsers() {
        try {
            logger.info("开始导出用户数据Excel");
            byte[] excelBytes = userService.exportUsers();
            
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setContentDispositionFormData("attachment", "users.xlsx");
            headers.setCacheControl("no-cache, no-store, must-revalidate");
            headers.setPragma("no-cache");
            headers.setExpires(0);
            
            logger.info("用户数据Excel导出成功，大小: {} 字节", excelBytes.length);
            return new ResponseEntity<>(excelBytes, headers, HttpStatus.OK);
        } catch (Exception e) {
            logger.error("导出用户数据Excel失败", e);
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
} 